import React, { Component} from 'react';
import { DatePicker, Row, Col } from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';

moment.locale('zh-cn');

class CascadeDatePicker extends Component {
  constructor(props) {
    super(props);
    const value = props.value || [];
    this.state = {
      startDate: value[0],
      endDate: value[1],
    };
  }

  componentWillReceiveProps(nextProps) {
    let value = nextProps.value;
    this.setState({
        startDate: value ? value[0] : null,
        endDate: value ? value[1] : null
    });
  }

  disabledStartDate = startDate => {
    const endDate = this.state.endDate;
    if (!startDate || !endDate) {
      return false;
    }
    return startDate.valueOf() > endDate.valueOf();
  };

  disabledEndDate = endDate => {
    const startDate = this.state.startDate;
    if (!endDate || !startDate) {
      return false;
    }
    return endDate.valueOf() < startDate.valueOf();
  };

  onChange = changedValue => {
    const onChange = this.props.onChange;
    this.setState(changedValue, () => {
      if (onChange) {
        const tempDateRange = Object.assign({}, this.state, changedValue);
        onChange([tempDateRange.startDate, tempDateRange.endDate]);
      }
    });
  };

  onStartChange = startDate => {
    this.onChange({ startDate });
  };

  onEndChange = endDate => {
    this.onChange({ endDate });
  };

  render() {
    let { placeholder } = this.props;
    placeholder = placeholder || {
      startDateHolder: '开始时间',
      endDateHolder: '结束时间',
    };

    return (
      <div style={{ display: 'flex', alignItems: 'center' }}>
        <div style={{ flex: '1'}}>
          <DatePicker
            {...this.props}
            disabledDate={this.disabledStartDate}
            value={this.state.startDate}
            allowClear={false}
            style={{ width: '100%' }}
            width={'100%'}
            placeholder={placeholder.startDateHolder}
            disabled={this.props.disabled}
            onChange={this.onStartChange}
          />
        </div>
        <div style={{ width: '15px', textAlign: 'center' }}>
          <span>-</span>
        </div>
        <div style={{ flex: '1' }}>
          <DatePicker
            {...this.props}
            disabledDate={this.disabledEndDate}
            value={this.state.endDate}
            placeholder={placeholder.endDateHolder}
            allowClear={false}
            style={{ width: '100%' }}
            disabled={this.props.disabled}
            onChange={this.onEndChange}
          />
        </div>
      </div>
    );
  }
}

export default CascadeDatePicker;
